package com.poker.controller;

import com.poker.consts.Consts;
import com.poker.entity.News;
import com.poker.service.NewsService;
import com.poker.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * @Author: yuanZ;
 * @Date: 2018/10/11 15:39;
 * @Description: 新闻管理;
**/
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController {

    @Resource
    private NewsService newsService;

    @RequestMapping("/list")
    public String list(Model model, News news,
                       @RequestParam(defaultValue = "0") Integer page,
                       @RequestParam(defaultValue = "50") Integer size) {
        Page<News> data = newsService.findNewsNoCriteria(page, size);

        model.addAttribute("data", data);
        model.addAttribute("news", news);
        return managerPage("news/list");
    }

    @RequestMapping("/findQuery")
    public String findQuery(Model model , News news,
                            @RequestParam(defaultValue = "0") Integer page,
                            @RequestParam(defaultValue = "50") Integer size) {
        Page<News> data = newsService.findNewsCriteria(page, size, news);

        model.addAttribute("data", data);
        model.addAttribute("news", news);
        return managerPage("news/list");
    }

    @RequestMapping("/edit")
    public String edit(Model model, String id, String editType) {
        News news = new News();

        if (Consts.EditType.EDIT.equals(editType)) news = newsService.getById(id);

        model.addAttribute("news", news);
        model.addAttribute("editType", editType);
        return managerPage("news/edit");
    }

    @ResponseBody
    @RequestMapping("/doEdit")
    public String doEdit(News news) {
        if (Misc.isEmpty(news) || Misc.isEmpty(news.getId())) toJson(false, "编辑信息为空", null);

        newsService.update(news);

        return toJson(true, "success", null);
    }

    @ResponseBody
    @RequestMapping("/add")
    public String add(News news) {
        if (Misc.isEmpty(news)) return toJson(false, "添加信息为空", null);

        newsService.saveNewsAndContent(news);

        return toJson(true, "success", null);
    }

    @RequestMapping("/delete")
    public String delete(String id, Integer page) {
        if (Misc.isEmpty(id)) return toJson(false, "id信息为空", null);

        if (Misc.isEmpty(page)) return toJson(false, "page信息为空", null);

        News news = newsService.getById(id);
        if (Misc.isEmpty(news)) return toJson(false, "目标信息不存在", null);

        newsService.deleteNewsAndContent(news);

        return redirect("/news/list?page=" + page);
    }

}
